import struct
from collections import OrderedDict

from ..base import BaseParser
from ...helper import get_price


class GetMinuteTimeData(BaseParser):

    def setParams(self, market, code):
        code = code.encode('utf-8') if type(code) is str else code

        pkg = bytearray.fromhex(u'0c 1b 08 00 01 01 0e 00 0e 00 1d 05')
        pkg.extend(struct.pack('<H6sI', market, code, 0))

        self.send_pkg = pkg

    def parseResponse(self, body_buf):
        (num,) = struct.unpack('<H', body_buf[:2])

        last_price = 0

        pos = 4

        prices = []

        for i in range(num):
            price_raw, pos = get_price(body_buf, pos)
            reversed1, pos = get_price(body_buf, pos)

            vol, pos = get_price(body_buf, pos)
            last_price = last_price + price_raw

            price = OrderedDict(
                [
                    ('price', float(last_price) / 100),
                    ('vol', vol)
                ]
            )

            prices.append(price)

        return prices
